#!/usr/bin/env python
import logging
import wsgiref.handlers
from google.appengine.ext import webapp
from google.appengine.ext import db
from dbmodel import Competition
from dbmodel import Class
from dbmodel import Runner
import urllib
from google.appengine.api import memcache
from renderer import PlainRenderer
from datetime import datetime

class UpdateResultHandler(webapp.RequestHandler):
  def get(self, key = None):
    self.response.headers['Content-Type'] = 'text/xml'
    comp = memcache.get(key)
    if comp is None:
    	comp = db.get(key)
	memcache.set(key,comp,3600)

    if comp == None:
    	self.response.out.write('<response status="ERR" message="WRONG PASSWORD"/>')
    else:
	if comp.password == self.request.get('password'):
		cl = memcache.get(key + "_class_" + self.request.get('classname'))
		if cl is None:
			q = db.GqlQuery('SELECT * from Class WHERE competitionid = :1 and name = :2',comp.key(),self.request.get('classname'))
    			cl = q.get()
			memcache.set(key + "_class_" + self.request.get('classname'), cl, 3600)

		q = db.GqlQuery('SELECT * from Runner WHERE runnerClass = :1 and id = :2',cl,int(self.request.get('id')))
		runner = q.get()

		scontroltimes = self.request.get('splittimes').rsplit(',')
		scontrols = self.request.get('splitcontrols').rsplit(',')
		
		controlids = []
                controltimes = []
		if scontrols != None and len(scontrols) > 0:
			for i in scontrols:
				if i != None and i != '':
					controlids.append(int(i))

		if scontroltimes != None:
			for i in scontroltimes:
				if i != None and i != '':
					controltimes.append(int(i))

    		logging.debug("parsed splitcontrols")
		logging.debug(controlids)

    		if runner != None:
			runner.firstname = self.request.get('firstname')
			runner.lastname = self.request.get('lastname')
			runner.clubname = self.request.get('clubname')
			runner.totaltime = int(self.request.get('totaltime'))
			runner.status = int(self.request.get('status'))
			runner.changetime = datetime.now()
			runner.SplitControls = controlids
			runner.SplitTimes = controltimes
       			runner.put()
    		else:
			runner = Runner(firstname = self.request.get('firstname'), lastname = self.request.get('lastname'),
				clubname = self.request.get('clubname'),
				totaltime = int(self.request.get('totaltime')),
				status = int(self.request.get('status')),
				runnerClass = cl,
				SplitControls = controlids,
				SplitTimes = controltimes,
				changetime = datetime.now(),
				id = int(self.request.get('id')))
       			runner.put()

		#Update Memcache!  
		upd = memcache.get(key + "_" + self.request.get('classname') +"_lastrender")
		if upd == None:
			logging.debug("rerendering: " + self.request.get('classname'))
			rend = PlainRenderer()
			rend.renderResultList(key,self.request.get('classname'))

    		self.response.out.write('<response status="OK"/>')
	else:
		self.response.out.write('<response status="ERR" message="WRONG PASSWORD"/>')


class UpdateClassHandler(webapp.RequestHandler):
  def get(self, key = None):
    self.response.headers['Content-Type'] = 'text/xml'
    comp = db.get(key)

    if comp == None:
    	self.response.out.write('<response status="ERR" message="WRONG PASSWORD"/>')
    else:
	if comp.password == self.request.get('password'):
		q = db.GqlQuery('SELECT * from Class WHERE competitionid = :1 and name = :2',comp.key(),self.request.get('name'))

		controlnames = self.request.get('controlnames').split(',')
		scontrolids = self.request.get('controlids').split(',')
		
		controlids = []
		if scontrolids != None and len(scontrolids) > 0:
			for i in scontrolids:
				if i != None and i != '':
					controlids.append(int(i))
    		
    		cl = q.get()
    		if cl:
			logging.debug("updating class " + self.request.get('name'))
       			cl.ident = urllib.quote_plus(self.request.get('name').encode('utf-8'))
			cl.ControlNames = controlnames
			cl.ControlCodes = controlids
       			cl.put()       
    		else:
			logging.debug("creating class " + self.request.get('name'))
       			cl = Class(name = self.request.get('name'))
       			cl.ident = urllib.quote_plus(self.request.get('name').encode('utf-8'))
       			cl.competitionid = comp.key()
			cl.ControlNames = controlnames
			cl.ControlCodes = controlids
       			cl.put()
  
		logging.debug("cleaning memcache")
		#Update Memcache!  
		memcache.delete(key+"_classes")
		memcache.delete(key + "_class_" + self.request.get('name'))
		rend = PlainRenderer()
		rend.renderResultList(key,self.request.get('name'))

    		self.response.out.write('<response status="OK"/>')
	else:
		self.response.out.write('<response status="ERR" message="WRONG PASSWORD"/>')

class GetClassesHandler(webapp.RequestHandler):
  def get(self, key = None):
    self.response.headers['Content-Type'] = 'text/xml'
    self.response.out.write('<classes compid="%s">' % key)
    self.response.out.write('</classes>')

class ValidatePasswordHandler(webapp.RequestHandler):
  def get(self, compkey = None):
    self.response.headers['Content-Type'] = 'text/xml'
    comp = db.get(compkey)
    if comp == None:
        self.response.out.write('<response status="ERR" message="No competition given"/>')
    else:
	if comp.password == self.request.get('password'):
           self.response.out.write('<response status="OK"/>')
        else:
           self.response.out.write('<response status="ERR" message="WRONG PASSWORD"/>')
   

class GetCompetitionsHandler(webapp.RequestHandler):
  def get(self):
    self.response.headers['Content-Type'] = 'text/xml'
    comps = Competition.all().order('-date')
     
    self.response.out.write('<competitions>')
    more = True
    idx = 0
    while more:
	q=comps.fetch(offset=idx, limit=100)
	more = False
    	for comp in q:
        	self.response.out.write('<competition')
       		self.response.out.write(' name="%s" date="%s" organizer="%s" id="%s"' % (comp.name, comp.date, comp.organizer, comp.key()))
		self.response.out.write('/>')
		more = True
	idx += 100

    self.response.out.write('</competitions>')
    


def main():
  logging.getLogger().setLevel(logging.DEBUG)
  application = webapp.WSGIApplication([('/API/Competitions', GetCompetitionsHandler),
					(r'/API/Competitions/(.*)/Classes', GetClassesHandler),
					(r'/API/Competitions/(.*)/SetClass', UpdateClassHandler),
					(r'/API/Competitions/(.*)/SetResult', UpdateResultHandler),
					(r'/API/Competitions/(.*)/ValidatePassword', ValidatePasswordHandler)
					],
                                       debug=True)
  wsgiref.handlers.CGIHandler().run(application)


if __name__ == '__main__':
  main()
